package com.sc.datacollect.netty.server;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sc.datacollect.imple.HeavyMetal;
import com.sc.datacollect.imple.IProtocol;
import com.sc.datacollect.imple.IonChromatography;
import com.sc.datacollect.imple.OCEC;
import com.sc.datacollect.main.MainCollect;
import com.sc.datacollect.util.Common;
import com.sc.datacollect.util.MongoDb;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class DataTransferServerHandler extends ChannelInboundHandlerAdapter {
	
	private MongoDb mongodb = MainCollect.mongodb;
	private IProtocol iprotocol;
	
	private Logger log = Logger.getLogger(DataTransferServerHandler.class);
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		JSONObject result = new JSONObject();
		try {
			JSONObject obj = JSONObject.parseObject(String.valueOf(msg));
			String dstype = obj.getString("dsType");
			String dataSource = obj.getString("dataSource");
			String datatype = obj.getString("dataType");
			
			log.info(dataSource + "::::::" + obj);
			JSONArray data = obj.getJSONArray("data");
			
			if ("ITP".equals(dstype)) {
				if ("HM".equals(dataSource)) {
					iprotocol = new HeavyMetal(dstype, dataSource, datatype, data, mongodb);
				} else if ("IC".equals(dataSource)) {
					iprotocol = new IonChromatography(dstype, dataSource, datatype, data, mongodb);
				} else if ("OCEC".equals(dataSource)) {
					iprotocol = new OCEC(dstype, dataSource, datatype, data, mongodb);
				}
			}
			
			String ret = iprotocol.saveData();
			
			if (Common.EXCEPTIONCODE.equals(ret)) {
				result.put("code", Common.EXCEPTIONCODE);
				result.put("msg", "数据保存失败");
			} else {
				result.put("code", Common.SUCCESSCODE);
				result.put("msg", "成功");
			}
		} catch (Exception e) {
			log.info(e.getMessage());
			result.put("code", Common.EXCEPTIONCODE);
			result.put("msg", e.getMessage());
		} finally {
			ctx.writeAndFlush(result.toJSONString());
			result = null;
		}
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}
}
